package com.lc.luzhengtang.activity;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.lc.luzhengtang.BaseApplication;
import com.lc.luzhengtang.R;
import com.lc.luzhengtang.base.BaseActivity;
import com.lc.luzhengtang.bean.CommenBean;
import com.lc.luzhengtang.conn.ConnAddAddress2;
import com.lc.luzhengtang.util.LovelyToast;
import com.lc.luzhengtang.util.MyUtils;
import com.lc.luzhengtang.view.ShowCityPicker;
import com.lljjcoder.citypickerview.widget.CityPicker;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.helper.util.UtilMatches;

import org.yapp.utils.permission.PermissionUtil;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.lc.luzhengtang.R.id.editText_name;
import static com.lc.luzhengtang.R.id.editText_shouhuodetail;
import static com.lc.luzhengtang.R.id.text_provice;

/**
 * Created by Administrator on 2017/5/26.
 */
public class AddAddress extends BaseActivity {

    @BindView(R.id.img_news)
    ImageView imgNews;
    @BindView(R.id.text_submit)
    TextView textSubmit;
    @BindView(editText_name)
    EditText editTextName;
    @BindView(R.id.edit_telephone)
    EditText editTelephone;
    @BindView(text_provice)
    TextView textProvice;
    @BindView(R.id.layouy_dingwei)
    LinearLayout layouyDingwei;
    @BindView(editText_shouhuodetail)
    EditText editextShouhuodetail;
    @BindView(R.id.editText_shouhuoperson)
    TextView editTextShouhuoperson;
    @BindView(R.id.img_address_add)
    CheckBox imgAddressAdd;
    //三级联动省市区
    private String province;
    private String city;
    private String district;

    private String status = "0";
    public AMapLocationClientOption mLocationOption = null;
    private AMapLocationClient mlocationClient = null;

    /**
     * 定位监听
     */
    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation location) {
            if (null != location) {

                StringBuffer sb = new StringBuffer();
                //errCode等于0代表定位成功，其他的为定位失败，具体的可以参照官网定位错误码说明
                if (location.getErrorCode() == 0) {
                    sb.append("定位成功" + "\n");
                    sb.append("定位类型: " + location.getLocationType() + "\n");
                    sb.append("经    度    : " + location.getLongitude() + "\n");
                    sb.append("纬    度    : " + location.getLatitude() + "\n");
                    sb.append("精    度    : " + location.getAccuracy() + "米" + "\n");
                    sb.append("提供者    : " + location.getProvider() + "\n");

                    sb.append("速    度    : " + location.getSpeed() + "米/秒" + "\n");
                    sb.append("角    度    : " + location.getBearing() + "\n");
                    // 获取当前提供定位服务的卫星个数
                    sb.append("星    数    : " + location.getSatellites() + "\n");
                    sb.append("国    家    : " + location.getCountry() + "\n");
                    sb.append("省            : " + location.getProvince() + "\n");


                    sb.append("市            : " + location.getCity() + "\n");
                    sb.append("城市编码 : " + location.getCityCode() + "\n");
                    sb.append("区            : " + location.getDistrict() + "\n");
                    sb.append("区域 码   : " + location.getAdCode() + "\n");
                    sb.append("地    址    : " + location.getAddress() + "\n");
                    sb.append("兴趣点    : " + location.getPoiName() + "\n");
                    //定位完成的时间
                    sb.append("定位时间: " + MyUtils.formatUTC(location.getTime(), "yyyy-MM-dd HH:mm:ss") + "\n");
                } else {
                    //定位失败
                    sb.append("定位失败" + "\n");
                    sb.append("错误码:" + location.getErrorCode() + "\n");
                    sb.append("错误信息:" + location.getErrorInfo() + "\n");
                    sb.append("错误描述:" + location.getLocationDetail() + "\n");
                }
                //定位之后的回调时间
                sb.append("回调时间: " + MyUtils.formatUTC(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss") + "\n");

                //解析定位结果，
                String result = sb.toString();
//                tvResult.setText(result);
                Log.d(result, "3333333333333333");
//                text_provice
                province = location.getProvince();
                city = location.getCity();
                district = location.getDistrict();
                textProvice.setText(location.getProvince() +location.getCity() + location.getDistrict());

//                Toast.makeText(AddAddress.this, location.getCity(), Toast.LENGTH_SHORT).show();
            } else {
//                tvResult.setText("定位失败，loc is null");
//                Log.d(result, "3333333333333333");
                Toast.makeText(AddAddress.this, "定位失败", Toast.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addaddress);
        ButterKnife.bind(this);
        PermissionUtil

                .with(AddAddress.this)

                .permissions(

                        PermissionUtil.PERMISSIONS_GROUP_LOACATION//定位授权

//                        PermissionUtil.PERMISSIONS_GROUP_CONTCATS//获取联系人授权

                ).request();
        imgAddressAdd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    status = "1";
                } else {
                    status = "0";
                }
            }
        });
       
        mlocationClient = new AMapLocationClient(getApplicationContext());
        mlocationClient = new AMapLocationClient(this);
//初始化定位参数
        mLocationOption = new AMapLocationClientOption();
//设置定位监听
        mlocationClient.setLocationListener(locationListener);
//设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
//设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
// 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
// 在定位结束后，在合适的生命周期调用onDestroy()方法
// 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
//启动定位
        mlocationClient.startLocation();
        sHA1(AddAddress.this);

    }

    public static String sHA1(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), PackageManager.GET_SIGNATURES);
            byte[] cert = info.signatures[0].toByteArray();
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] publicKey = md.digest(cert);
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < publicKey.length; i++) {
                String appendString = Integer.toHexString(0xFF & publicKey[i])
                        .toUpperCase(Locale.US);
                if (appendString.length() == 1)
                    hexString.append("0");
                hexString.append(appendString);
                hexString.append(":");
            }
            String result = hexString.toString();
            Log.d(result, "33333333333333333");
            Log.d(result, "33333333333333333");
            return result.substring(0, result.length() - 1);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    @OnClick({R.id.img_news, R.id.text_submit, editText_name, R.id.edit_telephone, text_provice, R.id.layouy_dingwei, editText_shouhuodetail, R.id.editText_shouhuoperson, R.id.img_address_add})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_news:
                finish();
                break;
            case R.id.text_submit:
//                editText_name
                if (TextUtils.isEmpty(editTextName.getText().toString().trim())) {
                    LovelyToast.makeText(AddAddress.this, "收货人姓名不能为空", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                }else if (!isChineseChar(editTextName.getText().toString().trim())){
                    LovelyToast.makeText(AddAddress.this, "收货人姓名不正确请填写汉字", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                }


                else if (TextUtils.isEmpty(editTelephone.getText().toString())) {
                    LovelyToast.makeText(AddAddress.this, "手机号不能为空", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                } else if (!UtilMatches.checkMobile(editTelephone.getText().toString())) {
                    LovelyToast.makeText(AddAddress.this, "请输入正确的手机号码", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                } else if (TextUtils.isEmpty(textProvice.getText().toString())) {
                    LovelyToast.makeText(AddAddress.this, "请填写省市区", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                } else if (TextUtils.isEmpty(editextShouhuodetail.getText().toString())) {
                    LovelyToast.makeText(AddAddress.this, "请填写详细地址", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                } else {
                    sendData();
                    finish();
                }


                break;
            case editText_name:
                break;
            case R.id.edit_telephone:
                break;
            case text_provice:
                break;
            case R.id.layouy_dingwei:

//                hideSoftInput(layouyDingwei);
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(layouyDingwei.getWindowToken(), 0);

                final CityPicker cityPicker = new ShowCityPicker().show(AddAddress.this);
                //监听方法，获取选择结果
                cityPicker.setOnCityItemClickListener(new CityPicker.OnCityItemClickListener() {
                    @Override
                    public void onSelected(String... citySelected) {
                        mlocationClient.stopLocation();
                        province = citySelected[0];

                        city = citySelected[1];

                        district = citySelected[2];

//                        textProvice.setText(new StringBuilder().append(province).append("-").append(city).append("-").append(district).toString());
                        textProvice.setText(new StringBuilder().append(province).append(city).append(district).toString());
                    }

                    @Override
                    public void onCancel() {
                        cityPicker.hide();
                    }
                });
                break;
            case editText_shouhuodetail:
                break;
            case R.id.editText_shouhuoperson:
                break;
            case R.id.img_address_add:


                break;
        }
    }


    public void sendData() {
        new ConnAddAddress2(BaseApplication.basePreferences.readUid(), editTextName.getText().toString().trim(), editTelephone.getText().toString().trim(),

                new StringBuilder().append(province).append(city).append(district).toString(), editextShouhuodetail.getText().toString().trim(),

                status, new AsyCallBack<CommenBean>() {
            @Override
            public void onStart(int type) throws Exception {
                super.onStart(type);
            }

            @Override
            public void onSuccess(String toast, int type, Object o, CommenBean commenBean) throws Exception {
                super.onSuccess(toast, type, o, commenBean);
                LovelyToast.makeText(AddAddress.this, "添加收货地址成功", 0, LovelyToast
                        .SUCCESS, LovelyToast.SCALE);
                finish();
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);

            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
            }
        }


        ).execute(AddAddress.this, false);
    }



    public static boolean isChineseChar(String str){
        boolean temp = false;
        Pattern p= Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m=p.matcher(str);
        if(m.find()){
            temp =  true;
        }
        return temp;
    }

}
